package net.dgg.zz.production.completed.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.OrfApiService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.entity.Node;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.FlowService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.production.chargeback.dao.ZzProductOrderDao;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.dao.ProductNodeDao;
import net.dgg.zz.production.inProcess.dao.ProductNodeOperatingDao;
import net.dgg.zz.production.inProcess.dao.ProductTimeStatusDao;
import net.dgg.zz.production.inProcess.entity.ProductNode;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import net.dgg.zz.production.suspend.service.ZzSubOrderService;
import net.dgg.zz.production.vo.CompletedOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

@Service
public class ZzCompletedOrderService extends BaseService {
    @Autowired
    private ZzSubOrderService scSubOrderService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private ZzProductOrderDao zzProductOrderDao;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private ZzInProcessService zzInProcessService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;



    public List<Map> query(Map paras) {
        extraFilter(paras);
        if (null == paras.get("orderColumn")) {
            paras.put("orderDir", "desc");
            paras.put("orderColumn", "updateTime");
        }
        return scSubOrderService.queryOverOrder(paras);
    }

    public int count(Map paras) {
        extraFilter(paras);
        return scSubOrderService.queryOverOrderCount(paras);
    }

    private void extraFilter(Map paras) {
        String[] statusArray = new String[3];
        statusArray[0] = ScProductConstant.SC_ORDER_OVER;
        statusArray[1] = ScProductConstant.SC_ORDER_OVER_OVERDUE;
        statusArray[2] = ScProductConstant.SC_ORDER_OVER_FORCE;
        paras.put("statusArray", statusArray);
        paras.put("dataAuthority", "zzsc_sc_completed");
    }

    /**
     * 结项生产订单
     */
    public void updateJunctionsOrder(Long id) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        Assert.notNull(userEntity, "未获取到登陆人，请重新登录！");
        Assert.notNull(id, "生产订单ID不能为空！");
        ProductOrder scProductOrder = this.zzProductOrderDao.getById(Long.valueOf(id));
        Assert.notNull(scProductOrder, "未查询到此生产订单，请刷新列表！");
        //Assert.isTrue(scProductOrder.getFlowUserId().equals(userEntity.getId()), "您没有权限，只能流程人员才能操作结项！");
        scProductOrder.setStatus(ScProductConstant.SC_ORDER_JUNCTIONS);
        //结项时间
        scProductOrder.setOverEndTime(new Date());
        this.updateOpt(scProductOrder, userEntity);
        zzProductOrderDao.update(scProductOrder);

        //操作记录
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
        systemRecord.setWorkId(scProductOrder.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setSource("2");//来源生产
        systemRecord.setOperateType("38");//操作类型 : 结项
        systemRecordService.save(systemRecord);

        //子订单完结调用子订单完结接口
        zzInProcessService.updateOrderBusiness(scProductOrder, userEntity, "ORF_BDZT_1");
        //判断生产子订单是否全部证书完结
        Integer status = 1;
        List<ProductOrder> scProductOrderList = zzProductOrderDao.query(new HashMap() {{
            put("orderId", scProductOrder.getOrderId());
        }});
        for (ProductOrder productOrder : scProductOrderList) {
            if (productOrder.getId().equals(scProductOrder.getId())) { //去除本次修改的
                continue;
            }
            if (!(productOrder.getStatus().equals(ScProductConstant.SC_ORDER_JUNCTIONS))
                    && !(productOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_CERTIFICATE))) { //不是结项和证书完结的
                status++;
            }
        }
        //证明全部已经完结
//        if (status == 1) {
//            //调同步接口
//            orfApiService.updateOrder(scProductOrder.getOrderId(), userEntity.getId(), "ORF_DDZT_6", null);
//        }
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(scProductOrder.getCustomerId());
        customerRecord.setTableName("zzsc_product_order");
        customerRecord.setTableId(scProductOrder.getId());
        customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE15);
        customerRecord.setCreaterId(userEntity.getId());
        customerRecord.setContent("生产结项");
        MQMessageSendUtil.ucMessageSend(customerRecord);

        //提交之后，将订单信息同步到企大顺生产中心
        MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  userEntity);

        String msgConent="您好，您的客户"+scProductOrder.getCustomerName()+"订单"+scProductOrder.getOrderNo()
                +"办理的"+scProductOrder.getScProductOrderNo()+"业务，订单已结项,请及时确认处理";
        commonService.sendQgjMessage(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
    }

    /**
     * 根据条件查询记录-导出
     *
     * @param params
     * @return
     */
    public List<CompletedOrderVo> findByParamsList(Map params) throws Exception {
        List<CompletedOrderVo> voList = new LinkedList<>();
        List<Map> srList = this.query(params);
        for (int i = 0; i < srList.size(); i++) {
            CompletedOrderVo vo = new CompletedOrderVo();
            vo.setSignOrgName(String.valueOf(srList.get(i).get("signOrgName") == null ? "" : srList.get(i).get("signOrgName")));
            vo.setOrderNo(String.valueOf(srList.get(i).get("orderNo") == null ? "" : srList.get(i).get("orderNo")));
            vo.setScProductOrderNo(String.valueOf(srList.get(i).get("scProductOrderNo") == null ? "" : srList.get(i).get("scProductOrderNo")));
            vo.setCustomerName(String.valueOf(srList.get(i).get("customerName") == null ? "" : srList.get(i).get("customerName")));
            vo.setBusinessProductName(String.valueOf(srList.get(i).get("businessProductName") == null ? "" : srList.get(i).get("businessProductName")));
            vo.setProductName(String.valueOf(srList.get(i).get("productName") == null ? "" : srList.get(i).get("productName")));
            vo.setSignTime(String.valueOf(srList.get(i).get("signTime") == null ? "" : srList.get(i).get("signTime")));
            vo.setSignUserName(String.valueOf(srList.get(i).get("signUserName") == null ? "" : srList.get(i).get("signUserName")));
            vo.setSignUserOrgName(String.valueOf(srList.get(i).get("signUserOrgName") == null ? "" : srList.get(i).get("signUserOrgName")));
            vo.setFlowUserName(String.valueOf(srList.get(i).get("flowUserName") == null ? "" : srList.get(i).get("flowUserName")));
            vo.setFlowUserOrgName(String.valueOf(srList.get(i).get("flowUserOrgName") == null ? "" : srList.get(i).get("flowUserOrgName")));
            vo.setCompletedTime(String.valueOf(srList.get(i).get("completedTime") == null ? "" : srList.get(i).get("completedTime")));
            vo.setContractNo(String.valueOf(srList.get(i).get("contractNo") == null ? "" : srList.get(i).get("contractNo")));
            vo.setCompanyName(String.valueOf(srList.get(i).get("companyName") == null ? "" : srList.get(i).get("companyName")));
            voList.add(vo);
        }
        return voList;
    }


    public List<Map> getCheckCloseAuditOrder(List<Long> ids) {
        return scSubOrderService.getCheckCloseAuditOrder(ids);
    }

    public void batchCloseAudit(List<Long> ids, Integer type, String remark) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        Assert.notNull(userEntity, "未获取到登陆人，请重新登录！");
        if(type.equals(1)){
            ids.forEach(id -> {
                ProductOrder scProductOrder = zzInProcessService.getScProductOrderById(Long.valueOf(id));
                ProductTimeStatus scProductTimeStatus = productTimeStatusDao.selectByPrimaryKey(scProductOrder.getId());
                if ("强制完结".equals(scProductOrder.getCurrentNodeName())) {
                    scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_FORCE); //强制完结
                    scProductOrder.setCompletedTime(new Date());
                }
                //订单正常完结且没有超期的
                if ("完结".equals(scProductOrder.getCurrentNodeName()) && ScProductConstant.NORMAL.equals(scProductTimeStatus.getOrderTimeStatus())) {
                    scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER);//正常完结
                    scProductOrder.setCompletedTime(new Date());
                }//订单正常完结且已经超期的
                else if ("完结".equals(scProductOrder.getCurrentNodeName()) && ScProductConstant.TIME_OUT.equals(scProductTimeStatus.getOrderTimeStatus())) {
                    scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_OVERDUE); //超期完结
                    scProductOrder.setCompletedTime(new Date());
                }
                scProductOrder.setLastRemark(remark);
                this.updateOpt(scProductOrder, userEntity);
                zzProductOrderDao.update(scProductOrder);
                List<ProductNode> scProductNodes = new ArrayList<>();
                if(!StringUtils.isEmpty(scProductOrder.getCurrentNodeId())){
                    scProductNodes = productNodeDao.query(new HashMap<String, Object>() {{
                        put("id", scProductOrder.getCurrentNodeId());
                    }});
                }
                Map organizationEntity = commonMangerExtService.findOrg(userEntity.getOrgId());
                ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员部门信息！");
                Integer  timeType= scProductTimeStatus.getNodeProcessTimeType() == null ? scProductNodes.get(0).getIsNaturalorWorkday():Integer.valueOf(scProductTimeStatus.getNodeProcessTimeType());
                Integer  processTime= scProductTimeStatus.getNodeProcessTime() == null ? scProductNodes.get(0).getHandleDate()/24 :scProductTimeStatus.getNodeProcessTime();
                ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
                scProductNodeOperating.setId(DggKeyWorker.nextId());
                scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                scProductNodeOperating.setScProductOrderId(scProductOrder.getId());
                scProductNodeOperating.setScProductOrderNo(scProductOrder.getScProductOrderNo());
                scProductNodeOperating.setFlowOrgId(Long.valueOf(organizationEntity.get("id").toString()));
                scProductNodeOperating.setFlowOrgName(organizationEntity.get("name").toString());
                scProductNodeOperating.setFlowUserId(userEntity.getId());
                scProductNodeOperating.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
                scProductNodeOperating.setOrderStatus(scProductOrder.getStatus());
                scProductNodeOperating.setNodeId(scProductOrder.getCurrentNodeId());
                scProductNodeOperating.setNodeName(scProductOrder.getCurrentNodeName());
                scProductNodeOperating.setNodeProcessTimeType(timeType.toString()); //节点办理类型
                scProductNodeOperating.setNodeOpetateTime(new Date());
                //scProductNodeOperating.setIsExtract(node.getIsExtract());
                UserEntity currentUser = sessionManager.getCurrentUser();
                Map curOrg = commonMangerExtService.findOrg(currentUser.getOrgId());
                scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());
                scProductNodeOperating.setRemark("审核通过：完成完结节点");
                scProductNodeOperating.setStatus(1);
                //获取当前节点的配置的计算出的超期时间
                Date currentDate = null;
                if(null == scProductTimeStatus.getNodeEndTime()) {
                    currentDate = commonService.getDateFromStartByType(scProductOrder.getLatestEndNodeTime(),
                            processTime, scProductTimeStatus.getNodeSuspendMillisecond() == null ? 0 : scProductTimeStatus.getNodeSuspendMillisecond(),
                            timeType);
                }else{
                    currentDate=scProductTimeStatus.getNodeEndTime();
                }
                //判断当前节点是否超期
                if (currentDate.getTime() >= System.currentTimeMillis()) {
                    scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
                } else {
                    scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
                    String date = DateUtils.transTime(currentDate, new Date());
                    scProductNodeOperating.setNodeOverdueTime(date); //节点超期时间
                }
                scProductNodeOperating.setNodeProcessTime(scProductTimeStatus.getNodeProcessTime());
                scProductNodeOperating.setNodeStartTime(scProductTimeStatus.getNodeStartTime());
                scProductNodeOperating.setNodeEndTime(scProductTimeStatus.getNodeEndTime());
                productNodeOperatingDao.insert(scProductNodeOperating);
                //操作记录
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
                systemRecord.setWorkId(scProductOrder.getId());
                systemRecord.setWorkTableName("zzsc_product_order");
                systemRecord.setSource("2");//来源生产
                systemRecord.setOperateType("38");//操作类型 : 结项
                systemRecord.setRemarks(StringUtils.isNotEmpty(remark)? "审核通过："+remark:"完结审核通过");
                systemRecordService.save(systemRecord);
                String[] throughMsg = new String[]{scProductOrder.getScProductOrderNo()};
                Long qgjUserId = zzInProcessService.getQgjUserId(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode());
                //有企管家人员才发送审核成功消息
                if(null != qgjUserId){
                    cmsService.sendMessage(qgjUserId, 1L, throughMsg, "ZZSC_SC_THROUGH_ORDER", 1);
                }
            });
        }else {
            ids.forEach(id -> {
                ProductOrder scProductOrder = zzInProcessService.getScProductOrderById(Long.valueOf(id));
                if(StringUtils.isEmpty(scProductOrder)){
                    return;
                }
                scProductOrder.setCurrentNodeId(scProductOrder.getLatestEndNodeId());
                scProductOrder.setCurrentNodeName(scProductOrder.getLatestEndNodeName());
                scProductOrder.setLastRemark(remark);
                this.updateOpt(scProductOrder, userEntity);
                zzProductOrderDao.update(scProductOrder);
                //操作记录
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
                systemRecord.setWorkId(scProductOrder.getId());
                systemRecord.setWorkTableName("zzsc_product_order");
                systemRecord.setSource("2");//来源生产
                systemRecord.setOperateType("60");//操作类型 : 结项
                systemRecord.setRemarks(StringUtils.isNotEmpty(remark)?"审核驳回："+remark:"完结审核驳回");
                systemRecordService.save(systemRecord);
                String[] rejectedMsg = new String[]{scProductOrder.getScProductOrderNo(),StringUtils.isNotEmpty(remark)?remark:"生产完结审核驳回"};
                //通知流程人员
                cmsService.sendMessage(scProductOrder.getFlowUserId(), 1L, rejectedMsg, "ZZSC_SC_REJECTED_ORDER", 1);
                //获取企管家人员
                Long qgjUserId = zzInProcessService.getQgjUserId(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode());
                //有企管家人员才发送审核失败消息
                if(null != qgjUserId){
                    cmsService.sendMessage(qgjUserId, 1L, rejectedMsg, "ZZSC_SC_REJECTED_ORDER", 1);
                }
            });
        }
    }

}

